//
//  UIButton+Tap.m
//  Express
//
//  Created by lhongl on 2025/9/26.
//  Copyright © 2025 QM. All rights reserved.
//

#import "UIButton+Tap.h"
#import <objc/runtime.h>

static const void* buttonCallBack = &buttonCallBack;

@implementation UIButton (Tap)

- (void)addButtonTarget:(nullable id)target action:(SEL)action {
    [self addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [self addTarget:self action:@selector(touchDownAction:) forControlEvents:(UIControlEventTouchDown)];
    [self addTarget:self action:@selector(touchUpAction:) forControlEvents:(UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel | UIControlEventTouchDragOutside)];
}

/// 添加button点击事件
/// - Parameter callBack: 回调
- (void)addButtonActionCallBack:(buttonActionCallBack)callBack {
    [self addButtonActionCallBack:callBack forControlEvents:(UIControlEventTouchUpInside)];
    [self addTarget:self action:@selector(touchDownAction:) forControlEvents:(UIControlEventTouchDown)];
    [self addTarget:self action:@selector(touchUpAction:) forControlEvents:(UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel | UIControlEventTouchDragOutside)];
}

/// 添加button点击事件
/// - Parameters:
///   - callBack: 回调
///   - controlEvents: 点击状态
- (void)addButtonActionCallBack:(buttonActionCallBack)callBack forControlEvents:(UIControlEvents)controlEvents {
    [self setCallBack:callBack];
    [self addTarget:self action:@selector(buttonAction:) forControlEvents:controlEvents];
}


#pragma mark 事件
- (void)buttonAction:(UIButton *)btn {
    if (self.getCallBack) {
        self.getCallBack(btn);
    }
}

- (void)touchDownAction:(UIButton *)btn {
    btn.enabled = NO;
    btn.alpha = 0.5f;
}

- (void)touchUpAction:(UIButton *)btn {
    btn.enabled = YES;
    btn.alpha = 1.0f;
}

#pragma mark - getter & setter
- (void)setCallBack:(buttonActionCallBack)callBack {
    objc_setAssociatedObject(self, &buttonCallBack, callBack, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (buttonActionCallBack)getCallBack {
    return (buttonActionCallBack)objc_getAssociatedObject(self, &buttonCallBack);
}


@end
